<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序订单Id" prop="procedureWorkOrderId">
              <el-input v-model="formData.procedureWorkOrderId" placeholder="请输入工序订单Id" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产计划" prop="planId">
              <el-select v-model="formData.planId" placeholder="请输入计划编号进行搜索" filterable style="width: 100%" remote
                         :remote-method="planRemoteMethod" :loading="planLoading" @change="handlePlanChange">
                <el-option v-for="plan in planList" :key="plan.id" :label="plan.planNo" :value="plan.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer" @select="deptChange"
                          placeholder="选择所属部门" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="formData.productId" placeholder="请输入产品名称进行搜索" filterable style="width: 100%" remote
                         :remote-method="productRemoteMethod" :loading="productLoading" @change="handleProductChange">
                <el-option v-for="product in productList" :key="product.id" :label="product.productName"
                           :value="product.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品物料id" prop="materialId">
              <el-input v-model="formData.materialId" placeholder="请输入成品物料id" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序Id" prop="procedureId">
              <el-input v-model="formData.procedureId" placeholder="请输入工序Id" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select v-model="formData.deviceId" placeholder="请输入设备名称进行搜索" filterable style="width: 100%" remote
                         :remote-method="deviceRemoteMethod" :loading="deviceLoading" @change="handleDeviceChange">
                <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单数量" prop="workOrderQuantity">
              <el-input v-model="formData.workOrderQuantity" placeholder="请输入工单数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planBeginTime">
              <el-date-picker clearable v-model="formData.planBeginTime" type="date" value-format="timestamp"
                              placeholder="选择计划开始时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker clearable v-model="formData.planEndTime" type="date" value-format="timestamp"
                              placeholder="选择计划结束时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每日派工数量" prop="daySendWorkNumber">
              <el-input v-model="formData.daySendWorkNumber" placeholder="请输入每日派工数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as WorkOrderApi from '@/api/production/workorder';
import * as PlanApi from '@/api/production/plan';
import * as ProductApi from '@/api/basic/product';
import * as DeviceApi from '@/api/system/device';
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "WorkOrderForm",
  components: {
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        procedureWorkOrderId: undefined,
        planId: undefined,
        planNo: undefined,
        deptId: undefined,
        deptName: undefined,
        productId: undefined,
        productName: undefined,
        materialId: undefined,
        procedureId: undefined,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: undefined,
      },
      // 生产计划列表
      planList: [],
      // 生产计划加载状态
      planLoading: false,
      // 产品列表
      productList: [],
      // 产品加载状态
      productLoading: false,
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 部门列表
      deptList: [],
      // 表单校验
      formRules: {
        procedureWorkOrderId: [{required: true, message: '工序订单Id不能为空', trigger: 'blur'}],
        planId: [{required: true, message: '生产计划Id不能为空', trigger: 'blur'}],
        deptId: [{required: true, message: '车间Id不能为空', trigger: 'blur'}],
        productId: [{required: true, message: '产品Id不能为空', trigger: 'blur'}],
        materialId: [{required: true, message: '成品物料id不能为空', trigger: 'blur'}],
        procedureId: [{required: true, message: '工序Id不能为空', trigger: 'blur'}],
        deviceId: [{required: true, message: '设备Id不能为空', trigger: 'blur'}],
        workOrderQuantity: [{required: true, message: '工单数量不能为空', trigger: 'blur'}],
      },
    };
  },
  methods: {
    /** 部门节点规范化 */
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };
      return normalizedNode;
    },

    /** 获取部门列表 */
    async getDeptList() {
      try {
        const response = await listDept();
        this.deptList = this.handleTree(response.data, "id")[0].children;
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },

    /** 部门选择处理 */
    deptChange(e) {
      this.formData.deptName = e.name;
    },

    /** 生产计划远程搜索方法 */
    async planRemoteMethod(query) {
      this.planLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          planNo: query
        };
        const response = await PlanApi.getPlanPage(params);
        this.planList = response.data.list;
      } catch (error) {
        console.error('搜索生产计划失败', error);
        this.planList = [];
      } finally {
        this.planLoading = false;
      }
    },

    /** 处理生产计划选择 */
    handlePlanChange(planId) {
      const selectedPlan = this.planList.find(plan => plan.id === planId);
      if (selectedPlan) {
        this.formData.planNo = selectedPlan.planNo;
      } else {
        this.formData.planNo = undefined;
      }
    },

    /** 产品远程搜索方法 */
    async productRemoteMethod(query) {
      this.productLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          productName: query
        };
        const response = await ProductApi.getProductPage(params);
        this.productList = response.data.list;
      } catch (error) {
        console.error('搜索产品失败', error);
        this.productList = [];
      } finally {
        this.productLoading = false;
      }
    },

    /** 处理产品选择 */
    handleProductChange(productId) {
      const selectedProduct = this.productList.find(product => product.id === productId);
      if (selectedProduct) {
        this.formData.productName = selectedProduct.productName;
      } else {
        this.formData.productName = undefined;
      }
    },

    /** 设备远程搜索方法 */
    async deviceRemoteMethod(query) {
      this.deviceLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('搜索设备失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    /** 处理设备选择 */
    handleDeviceChange(deviceId) {
      const selectedDevice = this.deviceList.find(device => device.id === deviceId);
      if (selectedDevice) {
        this.formData.deviceName = selectedDevice.deviceName;
      } else {
        this.formData.deviceName = undefined;
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 加载部门列表
      await this.getDeptList();
      // 初始化搜索列表
      await this.planRemoteMethod('');
      await this.productRemoteMethod('');
      await this.deviceRemoteMethod('');

      // 修改时，设置数据
      if (id) {
        this.dialogTitle = "编辑工单";
        this.formLoading = true;
        try {
          const res = await WorkOrderApi.getWorkOrder(id);
          this.formData = res.data;
          // 如果有生产计划ID，需要显示对应的计划编号
          if (this.formData.planId) {
            await this.planRemoteMethod(this.formData.planNo || '');
          }
          // 如果有产品ID，需要显示对应的产品名称
          if (this.formData.productId) {
            await this.productRemoteMethod(this.formData.productName || '');
          }
          // 如果有设备ID，需要显示对应的设备名称
          if (this.formData.deviceId) {
            await this.deviceRemoteMethod(this.formData.deviceName || '');
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增工单";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await WorkOrderApi.updateWorkOrder(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await WorkOrderApi.createWorkOrder(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        procedureWorkOrderId: undefined,
        planId: undefined,
        planNo: undefined,
        deptId: undefined,
        deptName: undefined,
        productId: undefined,
        productName: undefined,
        materialId: undefined,
        procedureId: undefined,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
